package com.example.ktapplication.net

import com.example.ktapplication.AppGlobals
import com.franmontiel.persistentcookiejar.ClearableCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.example.ktapplication.net.interceptor.CookieInterceptor
import com.example.ktapplication.net.interceptor.RequestInterceptor
import com.example.ktapplication.net.interceptor.ResponseInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


object RetrofitClient {

    private const val BASE_URL = "https://www.wanandroid.com"
    private var cookieJar: ClearableCookieJar =
        com.franmontiel.persistentcookiejar.PersistentCookieJar(
            SetCookieCache(),
            SharedPrefsCookiePersistor(AppGlobals.getApplication())
        )

    private val okHttpClient = OkHttpClient.Builder()
        .callTimeout(30, TimeUnit.SECONDS)
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)// 重连
        .followRedirects(false)// 重定向
        .cookieJar(cookieJar)
        .addInterceptor(RequestInterceptor())
        .addInterceptor(ResponseInterceptor())
        .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        .addInterceptor(HttpLoggingInterceptor())
        .addInterceptor(CookieInterceptor())
        .build()

    private val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(okHttpClient)
        .build()

    fun <T> createService(serviceClass: Class<T>): T {
        return retrofit.create(serviceClass)
    }

    fun clearCookie(){
        cookieJar.clear()
        cookieJar.clearSession()
    }
}